<?php
namespace App\Models\Simple;

use CodeIgniter\Model;

/**
 * DatabaseModel persisted in a database
 */
class DatabaseModel extends SimpleModel
{
    protected $db;
    protected $table;

    /**
     * Constructor.
     * @param string|null $origin Name of the database table (equivalent to XML file path)
     * @param string      $keyField  Name of the primary key field
     * @param string|null $entity	Entity name meaningful to the persistence
     */
    public function __construct($origin = null, $keyField = 'id', $entity = null)
    {
        parent::__construct($origin, $keyField, $entity);
        $this->table = $origin; // Using origin as table name for consistency with XMLModel
        $this->db = \Config\Database::connect();
        $this->builder = $this->db->table($this->table);
        // and populate the collection
        $this->load();
    }

    /**
     * Load the collection state from the database
     */
    protected function load()
    {
        if ($this->table !== null) {
            $builder = $this->db->table($this->table);
            $query = $builder->get();

            $first = true;
            foreach ($query->getResult('array') as $row) {
                $record = (object) $row;
                $id = $record->{$this->keyField};
                $this->data[$id] = $record;

                if ($first) {
                    $this->fields = array_keys($row);
                    $first = false;
                }
            }
        }

        // rebuild the keys table
        $this->reindex();
    }

    /**
     * Store the collection state into the database
     */
    protected function store()
    {
        if ($this->table !== null) {
            $builder = $this->db->table($this->table);

            // Clear existing records
            $builder->delete();

            // Insert new records
            foreach ($this->data as $record) {
                $builder->insert((array)$record);
            }
        }
    }
    protected function store1($id)
    {
        if ($this->table === null) {
            return false;
        }
    
        // Initialize the database builder
        $builder = $this->db->table($this->table);
    
        // Check if the record exists in memory
        if (!isset($this->data[$id])) {
            return false;
        }
    
        // Extract the data object for the given ID
        $record = $this->data[$id];
    
        // Prepare the data to be updated in the database
        $updateData = [
            'name' => $record->name,
            'description' => $record->description,
            'link' => $record->link,
            'image' => $record->image,
            'city' => $record->city,
            'powers' => $record->powers,
            'weapon' => $record->weapon
        ];
    
        try {
            // Perform the update operation with a specific condition
            $builder->where('id', $id)->update($updateData);
    
            // Optionally, you can check if the update affected any rows
            if ($this->db->affectedRows() > 0) {
                return true;
            } else {
                return false; // No rows were affected, which might indicate an issue
            }
        } catch (\CodeIgniter\Database\Exceptions\DatabaseException $e) {
            log_message('error', 'Database error in store1: ' . $e->getMessage());
            return false;
        }
    }
}